import http.server
import json
import requests

# 钉钉机器人WebHook地址
webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=32efbe1cf5d7d9a81256e1cf044a700abe089d36f9350d2ea10d7b22d8ea1127'

class HarborWebhookHandler(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        # 检查请求的路径
        if self.path == '/harbor':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            
            # 打印Harbor webhook请求body
            print("Received Harbor webhook request body:")
            print(post_data.decode('utf-8'))

            # 解析JSON数据
            data = json.loads(post_data)
            
            # 提取镜像信息
            if data.get('type') == 'PUSH_ARTIFACT':
                resources = data['event_data']['resources']
                for resource in resources:
                    digest = resource['digest']
                    tag = resource['tag']
                    resource_url = resource['resource_url']
                    message_url = "http://example.com"  # 你可以设置一个实际的URL

                    # 构建钉钉机器人消息
                    message = {
                        "msgtype": "text",
                        "text": {
                            "content": f"镜像 {resource_url} 已推送，Digest 为 {digest}"
                        }
                    }

                    print("Sending DingTalk request body:")
                    print(json.dumps(message, indent=4))

                    # 发送POST请求到钉钉机器人
                    headers = {
                        'Content-Type': 'application/json'
                    }
                    response = requests.post(webhook_url, headers=headers, data=json.dumps(message))

                    # 打印响应结果
                    print(f"钉钉响应状态码: {response.status_code}")
                    print(f"钉钉响应内容: {response.text}")
            
            # 发送200响应
            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            self.wfile.write(b'OK')
        else:
            # 如果路径不是/harbor，返回404
            self.send_response(404)
            self.end_headers()

# 设置服务器地址和端口
server_address = ('', 9999)
httpd = http.server.HTTPServer(server_address, HarborWebhookHandler)

print('启动HTTP服务器，监听端口 9999...')
httpd.serve_forever()

